package com.banksoft.util;

import com.banksoft.admin.bean.ColorFormatter;
import com.banksoft.admin.bean.Mapper;
import com.banksoft.admin.bean.ValueFormatter;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author rongzhao.zhu
 * @version 2016/11/3.
 */
public class ExcelExportUtil {

    public static final int DefaultColumnWidth = 25;

    public static final int DefaultHeadFontSize = 12;

    public static final int DefaultContentFontSize =10;

    private static Logger log = LoggerFactory
            .getLogger(ExcelExportUtil.class);

    /**
     * 构建默认的maper
     * @param showNames
     * @param keys
     * @return
     */
    public static  List<Mapper> buildDefaultMapperList(String[] showNames, String [] keys){
        List<Mapper> mappers = new ArrayList<Mapper>(keys.length);
        for(int index = 0;index< keys.length;index++){
            Mapper mapper = new Mapper();
            mapper.setKey(keys[index]);
            mapper.setShow(showNames[index]);
            mappers.add(mapper);
        }
        return mappers;
    }

    public static void exportExcel(HttpServletRequest request,
                                   HttpServletResponse response,
                                   String title,
                                   List<Mapper> mapperList,
                                   List<Map<String,Object>> list,
                                   int defaultColumnWidth,
                                   int headFontSize
                                   ){
        try{
            HSSFWorkbook hssfWorkbook = buildHSSFWorkBook(defaultColumnWidth);
           //  createTitle(hssfWorkbook, headFontSize, title, mapperList.size() - 1);
            createHead(hssfWorkbook,headFontSize,mapperList);
            createContent(1,hssfWorkbook,mapperList,list);
            loadExcelFile(request,response,hssfWorkbook,title);
        }catch (Exception e){
            log.error("导出excel出错",e);
        }

    }
    private static void loadExcelFile(HttpServletRequest request,
                               HttpServletResponse response, HSSFWorkbook workbook, String fileName) {
        response.setContentType("applicat2ion/vnd.ms-excel");
        try {
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.setHeader("Content-disposition", "attachment;filename="
                    + fileName + ".xls");// 注意这里
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();

        }

        OutputStream os;
        try {
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            String simplename = e.getClass().getSimpleName(); // 注意这里的异常处理，和原来的有一点点
            // 不同，这是由于中文乱码的问题引起的
            if (!"ClientAbortException".equals(simplename)) {
                e.printStackTrace();
            }
        }

    }
    /**
     * 构建excel工作簿
     * @param columnWidth
     * @return
     */
    public  static HSSFWorkbook buildHSSFWorkBook(int columnWidth){
        if(columnWidth <= 0){
            columnWidth = DefaultColumnWidth;
        }
        HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
        HSSFSheet sheet = workbook.createSheet(); // 创建工作表
        sheet.setDefaultColumnWidth(columnWidth); // 设置工作表列宽
        return workbook;
    }

    /**
     *  构建头部
     * @param workbook
     * @param headFontSize
     * @param title
     * @param colSize
     */
    public static void createTitle( HSSFWorkbook workbook,int  headFontSize,String title,int colSize){
        HSSFSheet sheet = workbook.getSheetAt(0);
        HSSFRow row1 = sheet.createRow(0);
        HSSFCellStyle hssfCellStyle = buildHeadStyle(workbook,headFontSize);
        //起始行，起始列，结束行，结束列
        sheet.addMergedRegion(new CellRangeAddress( 0, 0, 0, colSize));
        HSSFCell nameCell = row1.createCell(0);
        nameCell.setCellValue(title); //  表格的第一行至第一行第七列显示的数据
        nameCell.setCellStyle(hssfCellStyle); // 样式，居中
    }

    /**
     *
     * @param workbook
     * @param headFontSize
     * @param mapperList
     */
    public static void createHead(HSSFWorkbook workbook,int  headFontSize,List<Mapper> mapperList){
        HSSFSheet sheet = workbook.getSheetAt(0);
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle hssfCellStyle = buildHeadStyle(workbook,headFontSize);
        for (int index = 0; index< mapperList.size();index++){
            Mapper mapper =  mapperList.get(index);
            HSSFCell nameCell = row.createCell(index);
            nameCell.setCellValue(mapper.getShow()); //  表格的第一行至第一行第七列显示的数据
            nameCell.setCellStyle(hssfCellStyle); // 样式，居中
        }

    }

    /**
     * 构建excelContent
     * @param beginRow
     * @param workbook
     * @param mapperList
     * @param list
     */
    public static void createContent(int beginRow,HSSFWorkbook workbook,
                                     List<Mapper> mapperList, List<Map<String,Object>> list){
        HSSFSheet sheet = workbook.getSheetAt(0);
        HSSFCellStyle cellStyle = buildContentStyle(workbook);
        for(int row =0;row< list.size();row++){
            HSSFRow hssfRow = sheet.createRow(beginRow+row);
            Map<String,Object> map  = list.get(row);
            for(int index = 0;index <mapperList.size();index++){
                Mapper mapper =  mapperList.get(index);
                HSSFCell nameCell = hssfRow.createCell(index);
                nameCell.setCellStyle(cellStyle);
                String key  = mapper.getKey();
                ValueFormatter valueFormatter = mapper.getValueFormatter();

                Object obj  = map.get(key);
                String value = "";
                if(valueFormatter != null){
                    value = valueFormatter.apply(obj);
                }else {
                    if(obj !=null){
                        value = obj.toString();
                    }else {
                        value ="";
                    }

                }
                nameCell.setCellValue(value);
                //设置单元格字体颜色
                ColorFormatter colorFormatter = mapper.getColorFormatter();
                if(colorFormatter != null){
                    HSSFCellStyle _cellStyle = buildContentStyle(workbook);
                    HSSFColor color = getColorStr(colorFormatter,obj);
                    if(color != null ){
                        HSSFFont hssfFont = buildHSSFFont(workbook,DefaultContentFontSize);
                        hssfFont.setColor(color.getIndex());
                        _cellStyle.setFont(hssfFont);
                        nameCell.setCellStyle(_cellStyle);
                    }
                }

            }
        }
    }




    /**
     * 构建表格头部样式
     * @param workbook
     * @return
     */
    public static HSSFCellStyle buildHeadStyle(HSSFWorkbook workbook,int headFontSize ){
        HSSFCellStyle headStyle = workbook.createCellStyle();
        HSSFFont headFont = buildHSSFFont(workbook,headFontSize);
        headStyle.setFont(headFont);
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        return headStyle;
    }

    /**
     * 构建内容style
     * @param workbook
     * @return
     */
    public static HSSFCellStyle buildContentStyle(HSSFWorkbook workbook){
        HSSFCellStyle headStyle = workbook.createCellStyle();
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        return headStyle;
    }
    /**
     * 构建表头字体
     * @param workbook
     * @return
     */
    private static HSSFFont buildHSSFFont (HSSFWorkbook workbook,int fontSize){
        if(fontSize <= 0){
            fontSize = DefaultHeadFontSize;
        }
        HSSFFont headfont = workbook.createFont();
        headfont.setFontName("黑体");
        headfont.setFontHeightInPoints((short) fontSize);// 字体大小
        headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
        return headfont;
    }

    private static HSSFColor getColorStr(ColorFormatter colorFormatter,Object value){
        return colorFormatter.getColor(value);
    }

}
